package com.atguigu.srb.gateway.filter;

import com.atguigu.srb.common.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();

        List<String> tokens = headers.get("token");
        if (tokens != null && !tokens.isEmpty()) {
            String token = tokens.get(0);
            if (!StringUtils.isEmpty(token) && JwtUtils.checkToken(token)) {
                Long userId = JwtUtils.getUserId(token);
                if (!StringUtils.isEmpty(userId.toString())) {
                    ServerHttpRequest mutatedRequest = request.mutate()
                            .header("userId", userId.toString())
                            .build();
                    ServerWebExchange mutatedExchange = exchange.mutate()
                            .request(mutatedRequest)
                            .build();
                    return chain.filter(mutatedExchange);
                }
            }
        }

        return chain.filter(exchange);
    }
}

